package com.zxbit.flash.ui.activity.auth;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.zxbit.flash.R;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.camera.CameraActivity;
import com.zxbit.flash.camera.PicturePreviewActivity;
import com.zxbit.flash.common.AuthRouter;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.DialogManager;
import com.zxbit.flash.common.GlideImageLoader;
import com.zxbit.flash.common.RealNameAuthData;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.mvpview.IdentityAuthMvpView;
import com.zxbit.flash.mvpview.ImgMvpView;
import com.zxbit.flash.permission.IPermisson;
import com.zxbit.flash.permission.Permission;
import com.zxbit.flash.presenter.IdentityAuthPresenter;
import com.zxbit.flash.presenter.ImgPresenter;
import com.zxbit.flash.bean.AuthInfoData;
import com.zxbit.flash.response.AuthInfoResponse;
import com.zxbit.flash.response.BlankResponse;
import com.zxbit.flash.response.CompareResultResponse;
import com.zxbit.flash.bean.IdentityData;
import com.zxbit.flash.response.IdentityResponse;
import com.zxbit.flash.utils.FileUtils;
import com.zxbit.flash.utils.ImageUtils;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.utils.UploadImageUtil;
import com.zxbit.flash.utils.toolutil.RegularExpression;
import com.zxbit.flash.view.dialog.FormDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import ai.advance.liveness.lib.http.entity.ResultEntity;
import ai.advance.liveness.sdk.activity.LivenessActivity;
import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 身份认证 分为2步 一步身份认证 一步活体认证
 */
@Route(name = "身份证认证", path = RouterMap.REAL_NAME_AUTH_PAGE)
public class IdentityAuthActivity extends BaseTitleActivity implements IdentityAuthMvpView, ImgMvpView, IPermisson {

    @BindView(R.id.iv_positive)
    ImageView iv_positive;
    @BindView(R.id.tv_next_step)
    TextView tv_next_step;
    @BindView(R.id.iv_nagative)
    ImageView ivNagative;
    @BindView(R.id.linOne)
    LinearLayout linOne;
    @BindView(R.id.linTwo)
    NestedScrollView linTwo;
    @BindArray(R.array.identity)  //绑定string里面array数组
            String[] identity;
    @Autowired(name = Constant.IS_BACK)
    boolean is_back;

    private IdentityAuthPresenter realNameAuthPresenter;
    private ImgPresenter imgPresenter;
    private Permission permission;
    private FormDialog formDialog;
    private IdentityData.IdentityBean identityBean; // 身份证信息
    private IdentityData.ImageInfoBean imageInfoBeanPositive;
    private IdentityData.ImageInfoBean imageInfoBeanNagative;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void onUIReady() {
        permission = new Permission(this, this);
        realNameAuthPresenter = new IdentityAuthPresenter(this);
        imgPresenter = new ImgPresenter(this);

        if (UserInfo.isShowUserInformation()) {
            realNameAuthPresenter.getIdentityInfo();
        }
        if (is_back) {
            tv_next_step.setText(R.string.save_change);
        }
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_auth_identity;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.auth_identity_title);
    }

    @OnClick({R.id.tv_next_step, R.id.iv_positive, R.id.tvTwo_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_positive:
                permission.authPermisson(Constant.PIC_TYPE_ID_CARD_POSITIVE);
                break;
            case R.id.tvTwo_next_step:
                //活体检测的下一步
                permission.uploadImage(Constant.PIC_TYPE_ID_CARD_NAGATIVE);
                break;
            case R.id.tv_next_step:
                commit();
                break;
            default:
                break;
        }
    }

    /**
     * 下一步
     */
    private void commit() {
        if (iv_positive.getDrawable() == null || identityBean == null) {
            ToastUtils.showShort(this, R.string.auth_id_card_positive_hint);
            return;
        }
        //TODO 先修改为
       /* if (!is_back) {
            showDialog();
        }*/
        showDialog();
    }

    private String checkForm() {
        identityBean = RealNameAuthData.getInstance().getAllData();
        if (TextUtils.isEmpty(identityBean.getRealName())) {
            return getStringResource(R.string.auth_type_real_name_hint);
        } else if (TextUtils.isEmpty(identityBean.getIdentityCardNum())) {
            return getStringResource(R.string.auth_type_real_id_card_num_hint);
        } else if (TextUtils.isEmpty(identityBean.getBloodType())) {
            return getStringResource(R.string.auth_type_blood_type_hint);
        } else if (TextUtils.isEmpty(identityBean.getReligion())) {
            return getStringResource(R.string.auth_type_religion_hint);
        } else if (TextUtils.isEmpty(identityBean.getGender())) {
            return getStringResource(R.string.auth_type_sex_hint);
        } else if (TextUtils.isEmpty(identityBean.getBirthday())) {
            return getStringResource(R.string.auth_type_birthday_hint);
        } else if (TextUtils.isEmpty(identityBean.getBirthPlace())) {
            return getStringResource(R.string.auth_type_birth_place_hint);
        } else if (TextUtils.isEmpty(identityBean.getProvince())) {
            return getStringResource(R.string.auth_type_province_hint);
        } else if (TextUtils.isEmpty(identityBean.getCity())) {
            return getStringResource(R.string.auth_type_city_hint);
        } else if (TextUtils.isEmpty(identityBean.getDistrict())) {
            return getStringResource(R.string.auth_type_district_hint);
        } else if (TextUtils.isEmpty(identityBean.getVillage())) {
            return getStringResource(R.string.auth_type_village_hint);
        } else if (TextUtils.isEmpty(identityBean.getAddress())) {
            return getStringResource(R.string.auth_type_address_hint);
        } else if (TextUtils.isEmpty(identityBean.getRt())) {
            return getStringResource(R.string.auth_type_rt_hint);
        } else if (TextUtils.isEmpty(identityBean.getRw())) {
            return getStringResource(R.string.auth_type_rw_hint);
        } else if (TextUtils.isEmpty(identityBean.getNationality())) {
            return getStringResource(R.string.auth_type_nationality_hint);
        } else if (TextUtils.isEmpty(identityBean.getMaritalStatus())) {
            return getStringResource(R.string.auth_type_marital_status_hint);
        } else if (TextUtils.isEmpty(identityBean.getOccupation())) {
            return getStringResource(R.string.auth_type_occupation_hint);
        } else if (TextUtils.isEmpty(identityBean.getExpiryDate())) {
            return getStringResource(R.string.auth_type_expiry_date_hint);
        }

        String check = RegularExpression.checkRegularExpression(identityBean.getIdentityCardNum()
                , RegularExpression.idnum, getStringResource(R.string.auth_type_id_num_error));
        if (!TextUtils.isEmpty(check)) {
            return check;
        }
        return null;
    }

    /**
     * 弹框确认
     */
    private void showDialog() {
        if (formDialog == null) {
            formDialog = new FormDialog(IdentityAuthActivity.this, R.style.normal_dialog,
                    identity, identityBean.toArray());
        }
        formDialog.setOnClickListener(new FormDialog.FormClickListener() {
            @Override
            public void onConfirmClick() {
                String str = checkForm();
                if (!TextUtils.isEmpty(str)) {
                    ToastUtils.showShort(IdentityAuthActivity.this, str);
                    return;
                }
                if (imageInfoBeanPositive != null) {
                    linOne.setVisibility(View.GONE);
                    linTwo.setVisibility(View.VISIBLE);
                    setTitleText(getStringResource(R.string.auth_liveness_title));
                }
                DialogManager.getManager().dismissDialog(formDialog);
            }
        });
        DialogManager.getManager().showDialogStack(formDialog);

        RealNameAuthData.getInstance().putAllData(identityBean);
    }

    /**
     * 提交结果
     *
     * @param response
     */
    @Override
    public void onGetDataNext(BlankResponse response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            ToastUtils.showShort(this, getStringResource(R.string.auth_liveness_success));
            AuthRouter.getInstance().jumpNextPager(this, RouterMap.LIVENESS_AUTH_PAGE);
        } else {
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    /**
     * 资料回退是查询回应结果
     */
    @Override
    public void onGetDataNext(AuthInfoResponse response) {
        dismissLoadingView(); // 获取
        if (response.getStatus() == Constant.HTTP_OK) {
            fillImgView(response.getData().getIdentity());
        } else {
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    /**
     * 对比接口
     */
    @Override
    public void onGetDataNext(CompareResultResponse response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            List<IdentityData.ImageInfoBean> imageInfoParams = new ArrayList();
            imageInfoParams.add(imageInfoBeanPositive);
            imageInfoParams.add(imageInfoBeanNagative);
            realNameAuthPresenter.saveIdentity(RealNameAuthData.getInstance().getAllData(),
                    imageInfoParams);
            showLoadingView();
        } else {
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    /**
     * 展示认证信息结果
     *
     * @param identityBean
     */
    private void fillImgView(AuthInfoData.IdentityBean identityBean) {
        dismissLoadingView();
        List<AuthInfoData.IdentityBean.IdentityImagesBean> imgList = identityBean
                .getIdentityImages();
        if (imgList == null || imgList.size() == 0) {
            return;
        }
        for (AuthInfoData.IdentityBean.IdentityImagesBean image : imgList) {
            if (Constant.PIC_TYPE_ID_CARD_POSITIVE == image.getFileType()) {
                GlideImageLoader.LoadImage(this, image.getImageUrl(), iv_positive);
            }
        }
        this.identityBean = new IdentityData.IdentityBean(identityBean);
    }

    /**
     * 上传接口
     *
     * @param identityResponse
     * @param type
     */
    @Override
    public void onGetDataNext(IdentityResponse identityResponse, int... type) {
        dismissLoadingView();
        if (identityResponse.getStatus() == Constant.HTTP_OK) {
            if (type.length > 0 && type[0] == 1) {
                identityBean = identityResponse.getData().getIdentity();
                imageInfoBeanPositive = identityResponse.getData().getImageInfo();
            }
            if (identityResponse.getData().getImageInfo().getFileType() == 2) {
                imageInfoBeanNagative = identityResponse.getData().getImageInfo();
                GlideImageLoader.LoadImage(this, imageInfoBeanNagative.getImageUrl(), ivNagative);
                commitAll();
            }
        } else {
            ToastUtils.showShort(this, identityResponse.getMessage());
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
        ToastUtils.showShort(this, getStringResource(R.string.auth_error));
    }

    /**
     * 点击拍摄身份证
     */
    @Override
    public void onSuccess(int result) {
        if (result == Constant.PIC_TYPE_ID_CARD_POSITIVE) {
            Intent intent = new Intent(this, CameraActivity.class);
            intent.putExtra(CameraActivity.TYPE, CameraActivity.TYPE_ID_CARD);
            startActivityForResult(intent, result);
        } else {
            Intent intent = new Intent(this, LivenessActivity.class);
            startActivityForResult(intent, Constant.PIC_TYPE_ID_CARD_NAGATIVE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.PIC_TYPE_ID_CARD_POSITIVE && resultCode == 0x1234) {
            File file = new File(data.getStringExtra("filename"));
            final String filename = data.getStringExtra("filename");
            if (file.length() > 0) {
                Uri PhotoUri = Uri.fromFile(file);
                //设置图片
                GlideImageLoader.LoadImage(this, PhotoUri, iv_positive);

                Bitmap bitmap = BitmapFactory.decodeFile(filename);
                iv_positive.setImageBitmap(bitmap);

                compressImgAndDisPlay(PhotoUri, Constant.PIC_TYPE_ID_CARD_POSITIVE);
            } else {
                Bitmap bitmap = ImageUtils.bytes2Bitmap(PicturePreviewActivity.getImage());
                if (null == bitmap || bitmap.getAllocationByteCount() == 0) {
                    bitmap = BitmapFactory.decodeFile(data.getStringExtra("filename"));
                }
                if (null != bitmap && bitmap.getAllocationByteCount() > 0) {
                    bitmap = UploadImageUtil.getUploadNeedBitmapBYSize(bitmap);
                    if (UploadImageUtil.checkBitmapSize(bitmap)) {
                        iv_positive.setImageBitmap(bitmap);
                        imgPresenter.uploadIdentityCardForBitmap(requestCode,bitmap);
                    } else {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                compressImgAndDisPlayForFileString(filename, Constant
                                        .PIC_TYPE_ID_CARD_POSITIVE);
                            }
                        }, 2500);
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            compressImgAndDisPlayForFileString(filename, Constant
                                    .PIC_TYPE_ID_CARD_POSITIVE);
                        }
                    }, 1500);
                }
            }
        } else if (requestCode == Constant.PIC_TYPE_ID_CARD_POSITIVE && resultCode == 2) {
            imageInfoBeanNagative = (IdentityData.ImageInfoBean) data.getSerializableExtra
                    ("imageInfoBeanNagative");
        } else if (requestCode == Constant.PIC_TYPE_ID_CARD_NAGATIVE && resultCode == RESULT_OK) {
            ResultEntity entity = data.getParcelableExtra("data");
            String base64Str = data.getStringExtra("image");

            if (entity.success) {
                if (FileUtils.base64ToImage(base64Str) != null) {
                    imgPresenter.uploadImg(2, FileUtils.base64ToImage(base64Str));
                }

            }
        }
    }

    /**
     * 提交所有数据
     */
    private void commitAll() {
        if (imageInfoBeanPositive == null || imageInfoBeanNagative == null) {
            ToastUtils.showShort(this, R.string.liveness_auth_not_auth_message);
            return;
        }
        realNameAuthPresenter.imgCompare(imageInfoBeanPositive.getImagePath(),
                imageInfoBeanNagative.getImagePath());
        showLoadingView();
    }

    /**
     * 压缩并上传
     */
    public void compressImgAndDisPlay(Uri sourceImgUri, final int compressType) {

        Luban.with(this).ignoreBy(500).load(sourceImgUri).setTargetDir(FileUtils.getCachePicDir1()
        ).setCompressListener(new OnCompressListener() {
            @Override
            public void onStart() {
                showLoadingView();
            }

            @Override
            public void onSuccess(File file) {
                if (compressType == Constant.PIC_TYPE_ID_CARD_POSITIVE) {
                    imgPresenter.uploadIdentityCard(file);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingView();
            }
        }).launch();

    }

    public void compressImgAndDisPlayForFileString(String filePath, final int compressType) {
        Luban.with(this)
                .ignoreBy(500)
                .load(filePath)
                .setTargetDir(FileUtils.getCachePicDir1())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        showLoadingView();
                    }

                    @Override
                    public void onSuccess(File file) {
                        if (compressType == Constant.PIC_TYPE_ID_CARD_POSITIVE) {
                            imgPresenter.uploadIdentityCard(file);
                        } else if (compressType == Constant.PIC_TYPE_ID_CARD_NAGATIVE) {
                            imgPresenter.uploadImg(compressType, file);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoadingView();
                    }
                }).launch();

    }
}
